<template>
  <header-nav-bar :bool="true"></header-nav-bar>
  <van-form class="loginForm" @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="phone"
          name="手机号"
          label="手机号"
          placeholder="手机号"
          :rules="[{ required: true,validator: validatorMessage  ,message: '请输入手机号'  }]"
      />

      <van-field name="rate" label="图型验证码">
        <template #input>
          <van-image
              v-if="imageFresh"
              ref="verifyImage"
              width="200"
              height="40"
              @click="refreshCode"
              :src="src"
              alt="点击刷新"
          />
        </template>
      </van-field>

      <van-field
          v-model="verifyCode"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
      />

    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>

    <span>如已注册，使用 <a href="#" @click="phoneLogin">手机号登录</a></span>
  </van-form>

  <van-dialog v-model:show="show" title="短信验证码"
              show-cancel-button
              :overlay="false"
              @confirm="handleConfirm"
              @cancel="handleCancel"
  >
    <!-- 密码输入框 -->
    <van-password-input
        :value="verificationCode"
        :focused="showKeyboard"
        @focus="keyboardShow = true"
    />
  </van-dialog>


  <van-number-keyboard
      :show="keyboardShow"
      @blur="keyboardShow = false"
      @input="onInput"
      @delete="onDelete"
  />
</template>

<script setup lang="ts">
import {kaptcha, verify, smsSend, login} from '@/service/login.js'
import {PasswordInput, NumberKeyboard, Dialog, Toast} from 'vant'
import headerNavBar from "@/components/HeaderNavBar.vue"
import {nextTick, onMounted, ref, watch} from "vue"
import {useRouter} from 'vue-router'
import {userStore} from '@/store/userStore.ts'

const router = useRouter()
const store = userStore()
const VanDialog = Dialog.Component;
const username = ref('')
const confirmPassword = ref('')
const password = ref('')
//手机号
const phone = ref('')
const showKeyboard = ref(true)
//短信验证码
const verificationCode = ref('')
const show = ref(false)
const keyboardShow = ref(false)
//静态验证码
const verifyCode = ref('')
const src = ref("")
const imageFresh = ref(true)


// ref
const verifyImage = ref(null)

const validatorMessage = (val: any) => {
  let reg = /^1[3-9][0-9]{9}$/
  if (!reg.test(val)) {
    return "请输入正确的手机号"
  }
  return
}

const onSubmit = async () => {

  let params = {
    "verifyCode": verifyCode.value
  }
  //1.验证静态验证码是否正确
  let res = await verify(params)
  if (res.data.code === 200) {
    Toast("验证成功")
    //2.发送短信验证码
    showKeyboard.value = true
    show.value = true
    let params = {
      "phone": phone.value
    }
    res = await smsSend(params)
    if (res.data.code != 200) {
      Toast("验证发送失败！")
    }

  }

}

watch(verificationCode, (newVal: any) => {
  if (newVal.length === 6 && newVal !== '123456') {

  } else {

  }
});


const phoneLogin = () => {

}

onMounted(async () => {
  getKaptcha()
})


const onInput = (value: any) => {
  if (verificationCode.value.length === 6) {
    return
  }
  verificationCode.value += value
};
const onDelete = () => {
  if (verificationCode.value.length === 0) {
    return
  }
  verificationCode.value = verificationCode.value.substring(0, verificationCode.value.length - 1)
}


const handleConfirm = async () => {
  //  3.登录 短信验证码
  let params = {
    "phone": phone.value,
    "verifyCode": verificationCode.value
  }
  let res = await login(params)
  if (res.data.code === 200) {
    //保存登录信息
    store.setPhone(phone.value)
    store.setLoginFlag(true)  //已登录

    let token = res.data.token
    let username = res.data.username
    $cookies.set("token", token)
    $cookies.set("username", username)
    // 命名的路由
    // router.push({ name: 'user', params: { userId: '123' }})
    // 带查询参数，变成 /register?userId=123
    // router.push({ path: 'register', query: { userId: '123' }})
    router.push({path: "/", query: {loginFlag: true, phone: phone.value}})
  } else {
    Toast("验证失败！")
  }
}
const handleCancel = () => {
  Toast('cancel')
  verificationCode.value = ""

}

const refreshCode = async () => {
  getKaptcha()
}

const getKaptcha = async () => {
  let res = await kaptcha()
  if (res.data.code == 200) {
    src.value = "data:image/png;base64," + res.data.data
  }


}

</script>

<style scoped>
.loginForm {
  position: absolute;
  top: 70px;
}
</style>